import JoinExpression from "./JoinExpression";
import WhereExpression from "./WhereExpression";
import MetaData from "./MetaData";
import BaseExpression from "./abstract/BaseExpression";
import FieldExpression from "./impl/FieldExpression";
import StringUtils from "../utils/StringUtils";
import ExtendExpression from "./abstract/ExtendExpression";
import UnchangedExpression from "./impl/UnchangedExpression";
import Expression from "./interface/Expression";
import TableQueryBuilder from "../core/TableQueryBuilder";

/** 选择表 */
class TableExpression extends BaseExpression {
    public type:"where" | "limit" | "abs" | "prefix" | "native" | "table" = "table";

    /** 操作的表 */
    protected tablename: Expression = new UnchangedExpression("");
    /** 表的别称 */
    protected alias: string = "";

    constructor(table: string | Expression, alias: string = '', metaData: MetaData,empty:boolean=false) {
        super(metaData);
        if(empty){
            // 创建空table
            metaData.expressionList = [];
            metaData.table = {} as TableExpression;
            // 清空后返回
            return this;
        }else{
            metaData.table = this;
            this.tablename = typeof table === 'string' ? new FieldExpression(table,metaData):table
        }
        this.alias = alias;
    }
    /** 这里也可能有子查询，那就把自己给他 */
    public table(name: string, alias?: string):TableExpression;
    public table(name: string | ((table: TableQueryBuilder) => any), alias: string = '') {
        return new TableQueryBuilder(this.metadata).table(name,alias);
    }

    toLocaSql(): string {
        return this.tablename.toLocaSql() + StringUtils.frontFill(this.alias, " ");
    }

    public setAlias(name: string) {
        this.alias = name;
    }

    public getAlias() {
        return this.alias || this.tablename.toLocaSql();
    }

    /** 子查询 */
    public subquery(callback: (table: TableExpression) => any, alias: string = "") {
        return ExtendExpression.subqueryFactory<TableExpression>(this, this.metadata, callback, alias)
    }

    /** 左连接查询 */
    public leftJoin(table: string, alias?: string) {
        return new JoinExpression(this.metadata, new FieldExpression(table, "left join"), alias)
    }

    /** 右连接查询 */
    public rightJoin(table: string, alias?: string) {
        return new JoinExpression(this.metadata, new FieldExpression(table, "right join"), alias);
    }

    /** 内连接查询 */
    public join(table: string, alias?: string): JoinExpression {
        return new JoinExpression(this.metadata, new FieldExpression(table, "join"), alias);
    }


    /** where 查询 */
    public where(left: string | Record<string, any>, right?: string | number, inn: string = '=') {
        return WhereExpression.and(this.metadata, left, right, inn)
    }
}

export = TableExpression;